package org.example.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.example.model.user.dtos.UserIdentityDto;
import org.example.model.user.entities.UserInfo;
import org.springframework.beans.BeanUtils;

import java.util.Calendar;

/**
 * jwt工具类
 */
public class JwtUtils {

    private static final String SING = "yjx";

    private static final String UserDetail = "UserDetail";
    /**
     * 生成token
     */
    public static String GenerateToken(UserInfo userInfo) {

        UserIdentityDto userIdentityDto = new UserIdentityDto();
        BeanUtils.copyProperties(userInfo, userIdentityDto);

        //token过期时间
        Calendar instance = Calendar.getInstance();
        // 7天后令牌token失效
        instance.add(Calendar.HOUR,24 * 7);
        String token = JWT.create()
                .withClaim(UserDetail, JSON.toJSONString(userIdentityDto))
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token是否合法（即是否已过期）
     */
    public static DecodedJWT Verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 解析token,获取其中的有效信息
     */
    public static String GetInfoFromToken(String token) {
        DecodedJWT decodedJWT = JwtUtils.Verify(token);
        return decodedJWT.getClaim(UserDetail).asString();
    }
}
